package com.gxitsky.classload.demo3;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class UrlClassLoadTest {
    private static Connection conn;

    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String account = "root";
        String key = "123456";
        Connection conn = getConn(url, account, key);
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from country limit 10");
        System.out.println(conn.getSchema());
    }

    // 定义一个获取数据库连接的方法
    public static Connection getConn(String url, String user, String pass) throws Exception {
        if (conn == null) {
            // 创建一个URL数组
            URL[] urls = {new URL("file:///D:/mysql-connector-java-8.0.27.jar")};
            // 以默认的ClassLoader作为父ClassLoader，创建URLClassLoader
            @SuppressWarnings("resource")
            URLClassLoader myClassLoader = new URLClassLoader(urls);
            // 加载MySQL的JDBC驱动，并创建默认实例
            Driver driver = (Driver) myClassLoader.loadClass("com.mysql.cj.jdbc.Driver").newInstance();
            // 创建一个设置JDBC连接属性的Properties对象
            Properties props = new Properties();
            // 至少需要为该对象传入user和password两个属性
            props.setProperty("user", user);
            props.setProperty("password", pass);
            // 调用Driver对象的connect方法来取得数据库连接
            conn = driver.connect(url, props);
        }
        return conn;
    }
}
